package com.itljm.cxrMarket.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName JwtUtil
 * @author ljm
 * @date 2024/11/4 17:20
 */
@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration.access-token}")
    private long accessTokenExpiration;

    @Value("${jwt.expiration.refresh-token}")
    private long refreshTokenExpiration;

    @Autowired
    private RedisUtil redisUtil;

    // 生成访问token
    public String generateAccessToken(String subject) {
        return getJwtBuilder(subject,accessTokenExpiration);
    }

    // 生成刷新token
    public String generateRefreshToken(String subject) {
        String jwtBuilder = getJwtBuilder(subject,refreshTokenExpiration);
        redisUtil.setCacheObject("RefreshToken:" + subject, jwtBuilder);
        return jwtBuilder;
    }

    private String getJwtBuilder(String subject,long expiration) {
        return Jwts.builder()
                .setSubject(subject)   // 主体信息
                .setIssuer("ljm")     // 签发者
                .setExpiration(new Date(System.currentTimeMillis()+expiration))// 过期时间
                .signWith(SignatureAlgorithm.HS256, generalKey()) // 使用HS256对称加密算法签名, 第二个参数为秘钥
                .compact();
    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(secret);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseJWT(String jwt){
        try {
            return Jwts.parser()
                    .setSigningKey(generalKey())
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (Exception e){
            System.err.println("jwt解析日志：" + e.getMessage());
            throw e; // 或者抛出自定义异常
        }

    }

    /**
     * 验证token有效性
     * @param token
     * @return
     */
    public boolean validateToken(String token) {
        try {
            Claims claims = parseJWT(token);
            return !claims.getExpiration().before(new Date());
        } catch (Exception e) {
            return false; // Token已过期
        }
    }
}
